﻿@inject IHttpService _httpService
@inject IPopupService PopupService

@inject NavigationManager NavigationManager

@if (string.IsNullOrWhiteSpace(Model.Name) == false)
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip Title="@("编辑 " + Model.Name)"/>
}

<AutoSaveTip TItem="EditVideoMainPageViewModel" Item="Model" DataLoaded="DataLoaded" @ref="autoSave" />

<div>
    <CnGalWebSite.Shared.MasaComponent.Shared.Editors.Cards.EditSummaryTip Type="ExaminedNormalListModelType.Video" Class="mb-3" />
    @if (isReady == false)
    {
        <CnGalWebSite.Components.Progressings.ProgressingCard Page Fill />

    }
    else
    {
        <CnGalWebSite.Components.Containers.MasaTitleContainer Title="@($"编辑 {Model.Name}（Id:{Model.Id}）")" Icon="@IconType.Video.ToIconString()" Outline>
            <CnGalWebSite.Shared.MasaComponent.Shared.Editors.Videos.MainPageCard Model="Model" Class="mb-4" />
            <CnGalWebSite.Shared.MasaComponent.Shared.Editors.Buttons.SubmitButton OnSubmit="OnSubmit" Model="Model" />
        </CnGalWebSite.Components.Containers.MasaTitleContainer>
    }

</div>


@code {
    [Parameter]
    public string Id { get; set; }
    private EditVideoMainPageViewModel Model { get; set; } = new EditVideoMainPageViewModel();

    private bool isReady = false;

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    AutoSaveTip<EditVideoMainPageViewModel> autoSave { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            try
            {
                //获取文章信息
                Model = await _httpService.GetAsync<EditVideoMainPageViewModel>("api/videos/editmainpage/" + Id);

                isReady = true;
                StateHasChanged();
            }
            catch (Exception ex)
            {
                await ErrorHandler.ProcessError(ex, "获取编辑视频主页失败");
            }
        }
    }

    private async Task OnSubmit()
    {
        try
        {
            var obj = await _httpService.PostAsync<EditVideoMainPageViewModel, Result>("api/videos/editmainpage", Model);
            //判断结果
            if (obj.Successful == false)
            {

                await PopupService.ToastErrorAsync("编辑视频主页失败", obj.Error);
            }
            else
            {
                autoSave.Clean();

                await PopupService.ToastSuccessAsync("编辑视频主页成功", "编辑视频主页成功，等待审核通过");
                NavigationManager.NavigateTo("/videos/index/" + Model.Id);
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "编辑视频主页失败");
        }
    }

    private void DataLoaded(EditVideoMainPageViewModel model)
    {
        isReady = false;
        StateHasChanged();
        Model = model;
        isReady = true;
        StateHasChanged();
        
    }


}
